package com.jrx.anytxn.param.job.generalVerifyFile;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.config.VerifyFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.PrProductTable;
import com.jrx.anytxn.param.mapper.ext.ExtPrProductTableMapper;
import com.jrx.anytxn.param.service.partner.IPartnerGeneralService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * 生成累计对账文件，当日对账文件
 */
@Configuration
@EnableConfigurationProperties(VerifyFileConfig.class)
public class GeneralVerifyFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(GeneralVerifyFileConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private VerifyFileConfig verifyFileConfig;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Resource
    private ExtPrProductTableMapper extPrProductTableMapper;
    @Autowired
    private IPartnerGeneralService partnerGeneralService;


    @Bean
    public Job generalVerifyFileJob() {
        return jobBuilderFactory.get("generalVerifyFileJob")
                .start(generalVerifyFileStep())
                .build();
    }

    @Bean
    public Step generalVerifyFileStep(){
        return stepBuilderFactory.get("generalVerifyFileStep")
                .tasklet(generalVerifyFileTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet generalVerifyFileTasklet() {
        return (stepContribution, chunkContext) -> {
            String basePath = verifyFileConfig.getVerifyPath();
            ExecutorService service = Executors.newFixedThreadPool(16);

            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            String today = DateUtils.format(org.getToday(),"yyyyMMdd");
            List<PrProductTable> productTableList = extPrProductTableMapper.findByVerifyFileFlag(Constant.STATUS_1,Constant.STATUS_1);
            List<CompletableFuture<Void>> list = productTableList.stream().map(productTable ->
                    CompletableFuture.runAsync(() ->
                        {
                            try {
                                partnerGeneralService.createGeneralFile(productTable,basePath,org,today);
                            } catch (IOException e) {
                                logger.error("对账文件生成异常：",e);
                            }
                        }
                        , service)
            ).collect(Collectors.toList());
            long count = list.stream().map(CompletableFuture::join).count();
            logger.info("最终结果数{}",count);
            service.shutdown();
            return RepeatStatus.FINISHED;
        };
    }
}
